import { Provide } from '@midwayjs/core';
import { Repository } from 'typeorm';
import { ClassEntity } from '../../entity/firmware/class.entity';
import { School } from '../../entity/firmware/school.entity';
import { InjectEntityModel } from '@midwayjs/typeorm';

@Provide()
export class ClassService {
  @InjectEntityModel(ClassEntity)
  classRepo: Repository<ClassEntity>;

  @InjectEntityModel(School)
  schoolRepo: Repository<School>;

  // 创建班级
  async createClass(body) {
    const school = await this.schoolRepo.findOneBy({ id: body.school_id });
    if (!school) throw new Error('学校不存在')
    return await this.classRepo.save(body);
  }

  // 获取所有班级
  async getAllClasses(params) {
    const { edgroup_id, school_id, name, pageNum, pageSize } = params
    try {
      const query = this.classRepo.createQueryBuilder('class')
        .leftJoinAndSelect('class.school', 'school')
        .leftJoinAndSelect('school.edgroup', 'edgroup') // 关联 edgrp
      if (school_id) query.andWhere('class.school_id = :school_id', { school_id })
      if (edgroup_id) query.andWhere('school.edgrp_id = :edgroup_id', { edgroup_id })
      if (name) query.andWhere('class.name LIKE :name', { name: `%${name}%` })
      if (pageSize && pageNum) {
        query.skip((pageNum - 1) * pageSize).take(pageSize);
      }
      console.log('result', await query.getMany())
      // 查询总数 count
      const total = await query.getCount();
      // 返回数据
      return {
        total,
        data: await query.getMany(),
      };
    } catch (err) {
      console.log(err)
    }
  }

  // 根据 ID 获取单个班级
  async getClassById(id: number) {
    return await this.classRepo.findOne({ where: { id }, relations: ['school', 'school.edgroup'] });
  }

  // 更新班级
  async updateClass(updateData) {
    const classEntity = await this.getClassById(updateData.id);
    if (!classEntity) return null;

    Object.assign(classEntity, updateData);
    return await this.classRepo.save(classEntity);
  }

  // 删除班级
  async deleteClass(id: number) {
    const result = await this.classRepo.delete(id);
    return result.affected > 0;
  }
}
